/**
 * @Description: 异常捕获装饰器
 * @author Beon
 * @date 2021/1/4
*/
export class ErrorCatch{

    /**
     * promise捕获异常退出执行
     * @param {String} msg 提示报错信息
     * @returns {MethodDecorator}
     */
    static errorExit(msg?: string): MethodDecorator {
        return <T>(target: T, propertyKey: string, descriptor: PropertyDescriptor): void => {
            // 保存现有方法
            const setFunction = descriptor.value;

            // 重写方法
            descriptor.value = async (...args): Promise<any> => {
                try {
                    return await setFunction.call(target, ...args);
                } catch (e) {
                    const notice = `程序出现错误，请查看 ${propertyKey} 方法`;
                    msg = msg ? `${msg}: ${notice}` : notice;
                    console.log('\n' + msg.error);
                    console.log(e.stack.replace(e.toString(), '').debug);
                    process.exit(1);
                }
            };
        };
    }

    /**
     * promise捕获异常警告执行
     * @param {String} msg 提示警告信息
     * @returns {MethodDecorator}
     */
    static errorNotice(msg?: string): MethodDecorator {
        return (target: any, propertyKey: string, descriptor: PropertyDescriptor): void => {
            // 保存现有方法
            const setFunction = descriptor.value;

            // 重写方法
            descriptor.value = async (...args): Promise<any> => {
                try {
                    return await setFunction.call(target, ...args);
                } catch (e) {
                    const notice = `方法执行失败，对主流程无影响但可能导致信息不完整，请查看 ${propertyKey} 方法`;
                    msg = msg ? `${msg}: ${notice}` : notice;
                    console.log('\n' + msg.warning);
                    console.log(e.stack.replace(e.toString(), '').debug);
                    return e;
                }
            };
        };
    }
}
